import React from 'react'
import { HamburgerMenuIcon } from '@radix-ui/react-icons'
import { useParams } from 'react-router-dom'
import Equip from './equip'
import { Piece } from '@/types/piece'
import { Button } from '@/components/ui/button'
import Result from './result'
import { Card, CardFooter } from '@/components/ui/card'
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
import ShareForm from './share'
import { loadPieceComponentPackById } from '@/apis/piece'
import PieceComponentPackList, {
  PieceComponentPackListRef
} from './PieceComponentPackList'
import { usePieceStore } from '@/store/piece'
import { useNavigate } from 'react-router-dom'

const ROWS = 5 // 固定行数
const COLUMNS = 9 // 固定列数
const COLUMNS_JEWELRY = 6 // 首饰区列数
const PIECE_COUNT = ROWS * COLUMNS
const PIECE_JEWELRY_COUNT = ROWS * COLUMNS_JEWELRY // 首饰区数量
const TOTAL_COUNT = PIECE_COUNT + PIECE_JEWELRY_COUNT // 总数量 75

export default function PieceLayout() {
  const { id } = useParams()
  const navigate = useNavigate()
  const piecePackListRef = React.useRef<PieceComponentPackListRef>(null)
  // 初始化75
  const [pieces, setPieces] = React.useState<(Piece | undefined)[]>(
    Array(TOTAL_COUNT).fill(null)
  )
  // 移动端分享列表弹窗
  const [showShareList, setShowShareList] = React.useState(false)
  // 新增：存储title
  const [title, setTitle] = React.useState<string>('')
  // 根据id加载数据
  React.useEffect(() => {
    if (id) {
      const loadAndSetData = async () => {
        try {
          // 确保先加载所有碎片数据
          await usePieceStore.getState().loadAllPieces()

          // 然后加载指定ID的组件包数据
          const data = await loadPieceComponentPackById(Number(id))
          console.log('Loaded piece component pack:', data)

          if (data && data.title) {
            setTitle(data.title)
            document.title = data.title
          } else {
            setTitle('')
          }

          if (data && data.content) {
            try {
              const parsed = data.content.split(',').map((id) => Number(id))
              // 获取所有碎片（此时已经确保加载完成）
              const allPieces = usePieceStore.getState().storePieces
              // 按照 parsed 顺序查找对应的 Piece
              const filledPieces = parsed.map(
                (id) => allPieces.find((p) => p.id === id) || null
              )
              // 补齐长度
              setPieces([
                ...filledPieces,
                ...Array(TOTAL_COUNT - filledPieces.length).fill(null)
              ])
              // 检查首饰区是否有内容
              const jewelryPieces = filledPieces.slice(PIECE_COUNT, TOTAL_COUNT)
              const hasAnyJewelry = jewelryPieces.some((p) => p !== null)
              setHasJewelry(hasAnyJewelry)
            } catch (e) {
              // content不是json，忽略
              console.error('Error parsing content:', e)
            }
          }
        } catch (error) {
          console.error('Error loading data:', error)
        }
      }

      loadAndSetData()
    }
  }, [id])
  const [hasJewelry, setHasJewelry] = React.useState(false)
  // result的结果，3列，导出文本内容
  const [resultText, setResultText] = React.useState('')

  // 导出文本内容，合并装备和首饰
  const handleExport = () => {
    const equip = pieces.slice(0, PIECE_COUNT)
    const jewelry = pieces.slice(PIECE_COUNT, TOTAL_COUNT)
    const equipText = [
      '装备碎片',
      equip
        .filter(Boolean)
        .map((piece, idx) => {
          if (!piece) return ''
          return `${idx + 1}. ${piece.name}（${piece.alias}）P数:${
            piece.score ?? 0
          } 效果:${piece.describe ?? ''}`
        })
        .filter(Boolean)
        .join('\n')
    ]
      .filter(Boolean)
      .join('\n')
    const jewelryText = [
      '首饰碎片',
      jewelry
        .filter(Boolean)
        .map((piece, idx) => {
          if (!piece) return ''
          return `${idx + 1}. ${piece.name}（${piece.alias}）P数:${
            piece.score ?? 0
          } 效果:${piece.describe ?? ''}`
        })
        .filter(Boolean)
        .join('\n')
    ]
      .filter(Boolean)
      .join('\n')
    const text = [
      equipText,
      jewelryText,
      resultText ? '效果仅供参考\n' + resultText : ''
    ]
      .filter(Boolean)
      .join('\n\n')
    const blob = new Blob([text], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '装备与首饰.txt'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  // 重置所有碎片
  const handleReset = () => {
    setPieces(Array(TOTAL_COUNT).fill(null))
    setHasJewelry(false)
    setResultText('')
  }

  return (
    <main className="flex min-h-screen w-full items-center justify-center bg-gradient-to-br from-slate-100 to-slate-200 dark:from-neutral-900 dark:to-neutral-800">
      {/* 右侧悬浮的方案列表 - 仅在大屏时显示 */}
      <div className="hidden lg:block">
        <PieceComponentPackList
          ref={piecePackListRef}
          onSelect={(pack) => {
            if (pack.id !== Number(id)) {
              navigate(`/pieces/${pack.id}`)
            }
          }}
        />
      </div>
      {/* 移动端右侧按钮，点击弹出分享列表 */}
      <div className="fixed right-4 top-1/2 z-30 block lg:hidden">
        <Button
          size="icon"
          className="rounded-full border border-slate-200 bg-gradient-to-br from-blue-200 via-purple-200 to-pink-200 shadow-xl transition-all duration-200 hover:scale-110 hover:shadow-2xl dark:border-neutral-700 dark:bg-gradient-to-br dark:from-neutral-900 dark:to-neutral-800"
          onClick={() => setShowShareList(true)}
          aria-label="打开分享列表"
        >
          <span className="flex size-7 items-center justify-center">
            <HamburgerMenuIcon
              className="text-blue-500 dark:text-pink-300"
              width={28}
              height={28}
            />
          </span>
        </Button>
      </div>
      {/* 移动端分享列表弹窗 */}
      {showShareList && (
        <div
          className="fixed inset-0 z-40 flex items-center justify-center bg-black/40"
          onClick={() => setShowShareList(false)}
        >
          <div
            className="relative w-11/12 max-w-sm rounded-lg bg-white p-4 shadow-xl dark:bg-neutral-900"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              className="absolute right-2 top-2 text-xl text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
              onClick={() => setShowShareList(false)}
              aria-label="关闭"
            >
              ×
            </button>
            <PieceComponentPackList
              ref={piecePackListRef}
              onSelect={(pack) => {
                setShowShareList(false)
                if (pack.id !== Number(id)) {
                  navigate(`/pieces/${pack.id}`)
                }
              }}
            />
          </div>
        </div>
      )}
      <div className="mx-auto flex w-full max-w-4xl flex-col items-center justify-center gap-8 p-4 sm:p-8">
        <Card className="flex w-full flex-col gap-8 p-6">
          {/* 新增：显示title */}
          {title && (
            <div className="mb-2 text-center text-xl font-bold text-slate-700 dark:text-neutral-200">
              {title}
            </div>
          )}
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            {/* 左侧：返回按钮 */}
            <Button
              variant="outline"
              size="sm"
              className="flex items-center gap-2 self-start transition-all duration-200 hover:scale-105"
              onClick={() => navigate('/')}
            >
              <span>←</span>
              返回
            </Button>

            {/* 右侧：操作按钮组 */}
            <div className="flex items-center gap-2">
              <Button
                size="sm"
                variant="outline"
                className="border-red-200 text-red-600 transition-all duration-200 hover:scale-105 hover:bg-red-50 dark:border-red-800 dark:text-red-400 dark:hover:bg-red-950"
                onClick={handleReset}
              >
                重置
              </Button>
              <Button
                size="sm"
                variant="outline"
                className="transition-all duration-200 hover:scale-105"
                onClick={handleExport}
              >
                导出
              </Button>
              <ShareForm
                pieces={pieces}
                onShareSuccess={() => {
                  // 分享成功后刷新方案列表
                  piecePackListRef.current?.refresh()
                }}
              />
            </div>
          </div>
          {/* 装备和首饰区域，使用ScrollArea包裹 */}
          <ScrollArea className="h-[350px] w-full">
            <div className="flex w-full gap-6 p-2">
              {/* 装备区 */}
              <div className="flex-1">
                <div className="w-full">
                  <Equip
                    pieces={pieces.slice(0, PIECE_COUNT)}
                    columns={9}
                    name="装备"
                    columnNames={[
                      '头',
                      '衬衣',
                      '腰带',
                      '护腿',
                      '鞋子',
                      '护肩',
                      '铠甲',
                      '护手',
                      '武器'
                    ]}
                    onChange={(equipPieces) => {
                      setPieces((prev) => [
                        ...equipPieces,
                        ...prev.slice(equipPieces.length, TOTAL_COUNT)
                      ])
                    }}
                  />
                </div>
              </div>
              {/* 首饰区 */}
              <div className="flex-1">
                <div className="w-full">
                  <Equip
                    pieces={pieces.slice(PIECE_COUNT, TOTAL_COUNT)}
                    type={2}
                    name="首饰"
                    columnNames={[
                      '爪子',
                      '眼睛',
                      '翅膀',
                      '项链',
                      '左戒',
                      '右戒'
                    ]}
                    onChange={(jewelryPieces) => {
                      setHasJewelry(true)
                      setPieces((prev) => [
                        ...prev.slice(0, PIECE_COUNT),
                        ...jewelryPieces,
                        ...prev.slice(TOTAL_COUNT)
                      ])
                    }}
                    backgroundColor="bg-red-100"
                    columns={6}
                  />
                </div>
              </div>
            </div>
            <ScrollBar orientation="horizontal" />
          </ScrollArea>
          {/* 结果展示区，紧跟Tab内容区下方 */}
          <CardFooter className="mt-4 w-full">
            <div className="w-full overflow-x-auto">
              <Result
                pieces={pieces}
                hasJewel={hasJewelry}
                handle_result={setResultText}
                equipColumnNames={[
                  '头',
                  '衬衣',
                  '腰带',
                  '护腿',
                  '鞋子',
                  '护肩',
                  '铠甲',
                  '护手',
                  '武器'
                ]}
                jewelryColumnNames={[
                  '爪子',
                  '眼睛',
                  '翅膀',
                  '项链',
                  '左戒',
                  '右戒'
                ]}
              />
            </div>
          </CardFooter>
        </Card>
      </div>
    </main>
  )
}
